package com.dell.chen.servlet;

import com.dell.chen.pojo.Cart;
import com.dell.chen.pojo.CartItem;
import com.dell.chen.pojo.Flowers;
import com.dell.chen.service.FlowerService;
import com.dell.chen.service.Impl.FlowerServiceImpl;
import com.dell.chen.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author ：ChenwithIU
 * @date ：Created in 2020/12/3 15:44
 */
public class CartServlet extends BaseServlet{
    private FlowerService flowerService = new FlowerServiceImpl();

    /**
     * 加入到购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id1 = req.getParameter("id");

        //获取请求的参数  商品编号
        int id = WebUtils.parseInt(id1, 0);
//        int count = WebUtils.parseInt("count", 0);

//        req.setAttribute("count",count);

        //调用queryFlowerById 得到 商品信息
        Flowers flowers = flowerService.queryFlowerById(id);

        //把花商品信息 转换为 CartItem商品项
        CartItem cartItem = new CartItem(flowers.getId(),flowers.getName(),flowers.getPrice(),1,flowers.getImg_path(),flowers.getPrice());
        req.getSession().setAttribute("cartItem",cartItem);

        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //如果购物车为空
        if (cart == null) {
            //创建新的购物车
            cart = new Cart();
            //设置Session域中的 cart值
            req.getSession().setAttribute("cart", cart);
        }
        //添加到cart集合中
        cart.addItem(cartItem);

        System.out.println(cart);
        System.out.println("请求头Referer的值：" + req.getHeader("Referer"));
        // 最后一个添加的商品名称
        req.getSession().setAttribute("lastName", cartItem.getName());

        // 重定向回原来商品所在的地址页面
        resp.sendRedirect(req.getHeader("Referer"));
//        req.getRequestDispatcher("/pages/Floda/cart.jsp").forward(req,resp);
    }

    /**
     * 删除商品项
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id1 = req.getParameter("id");

        //获取请求的参数  商品编号
        int id = WebUtils.parseInt(id1, 0);

        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if (cart != null){
            cart.deleteItem(id);
            // 重定向回原来商品所在的地址页面
            resp.sendRedirect(req.getHeader("Referer"));
        }
    }

}
